package com.lingkang.dbtodoc.controller;

import cn.hutool.core.lang.Assert;
import com.lingkang.dbtodoc.constants.HttpCode;
import com.lingkang.dbtodoc.dto.ResponseResult;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author 绫小路
 * @date 2021/1/31 23:06
 * @description
 */
@Controller
public class CommonController {

  @Value("${user.nickname}")
  private String nickname;
  @Value("${user.username}")
  private String username;
  @Value("${user.password}")
  private String password;

  @Autowired
  private HttpServletRequest request;

  @GetMapping("")
  public String index() {
    if (request.getSession().getAttribute("username") == null) {
      return "redirect:/login";
    }
    return "redirect:/main";
  }

  @GetMapping("/main")
  public String main() {
    return "main";
  }

  @GetMapping("/about")
  public String about(){
    return "about";
  }

  @GetMapping("/login")
  public String login() {
    return "login";
  }

  @PostMapping("/login")
  @ResponseBody
  public ResponseResult login(String password, String username) {
    Assert.notBlank(password, "密码不能为空！");
    Assert.notBlank(username, "账号不能为空！");
    Assert.isTrue(username.equals(this.username), "账号错误！");
    Assert.isTrue(password.equals(this.password), "密码错误！");
    request.getSession().setAttribute("username", username);
    request.getSession().setAttribute("nickname", this.nickname);
    return new ResponseResult(HttpCode.OK, "登录成功！");
  }

  @GetMapping("/logout")
  public String logout() {
    request.getSession().invalidate();
    return "login";
  }

}
